<?php

declare(strict_types=1);

namespace App\Services;

use App\Services\Database;

final class Statistics
{
    public static function getDashboardStats(): array
    {
        $db = Database::pdo();
        $stats = [
            'total_posts' => 0,
            'total_users' => 0,
            'recent_posts' => [],
            'popular_posts' => [],
            'system_info' => [],
            'today_stats' => [
                'posts_created' => 0,
                'users_registered' => 0
            ]
        ];

        try {
            // 文章总数
            $stmt = $db->query("SELECT COUNT(*) as count FROM posts");
            $stats['total_posts'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'] ?? 0;

            // 用户总数
            $stmt = $db->query("SELECT COUNT(*) as count FROM users");
            $stats['total_users'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'] ?? 0;

            // 最近文章
            $stmt = $db->query("SELECT id, title, created_at FROM posts ORDER BY created_at DESC LIMIT 5");
            $stats['recent_posts'] = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

            // 今日统计
            $today = date('Y-m-d');

            $stmt = $db->prepare("SELECT COUNT(*) as count FROM posts WHERE DATE(created_at) = :today");
            $stmt->bindParam(':today', $today);
            $stmt->execute();
            $stats['today_stats']['posts_created'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'] ?? 0;

            $stmt = $db->prepare("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = :today");
            $stmt->bindParam(':today', $today);
            $stmt->execute();
            $stats['today_stats']['users_registered'] = $stmt->fetch(\PDO::FETCH_ASSOC)['count'] ?? 0;

            // 系统信息
            $stats['system_info'] = [
                'php_version' => PHP_VERSION,
                'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
                'database_version' => $db->query("SELECT VERSION() as version")->fetch(\PDO::FETCH_ASSOC)['version'] ?? 'Unknown',
                'memory_usage' => round(memory_get_usage(true) / 1024 / 1024, 2) . ' MB',
                'memory_limit' => ini_get('memory_limit'),
                'disk_free' => round(disk_free_space('.') / 1024 / 1024 / 1024, 2) . ' GB',
                'upload_max_filesize' => ini_get('upload_max_filesize'),
                'max_execution_time' => ini_get('max_execution_time') . 's'
            ];
        } catch (\Throwable $e) {
            error_log("Statistics error: " . $e->getMessage());
        }

        return $stats;
    }

    public static function getLogStats(): array
    {
        $stats = [
            'access_log_size' => 0,
            'app_log_size' => 0,
            'access_log_lines' => 0,
            'app_log_lines' => 0,
            'rate_limit_entries' => 0
        ];

        try {
            $accessLogFile = APP_ROOT . '/storage/logs/access.log';
            if (file_exists($accessLogFile)) {
                $stats['access_log_size'] = round(filesize($accessLogFile) / 1024, 2) . ' KB';
                $stats['access_log_lines'] = count(file($accessLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
            }

            $appLogFile = APP_ROOT . '/storage/logs/app.log';
            if (file_exists($appLogFile)) {
                $stats['app_log_size'] = round(filesize($appLogFile) / 1024, 2) . ' KB';
                $stats['app_log_lines'] = count(file($appLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
            }

            $rateLimitFile = APP_ROOT . '/storage/logs/rate_limit.json';
            if (file_exists($rateLimitFile)) {
                $data = json_decode(file_get_contents($rateLimitFile), true);
                $stats['rate_limit_entries'] = is_array($data) ? count($data) : 0;
            }
        } catch (\Throwable $e) {
            error_log("Log stats error: " . $e->getMessage());
        }

        return $stats;
    }

    public static function getRecentActivity(): array
    {
        $db = Database::pdo();
        $activities = [];

        try {
            // 最近的文章
            $stmt = $db->query("
                SELECT 'post' as type, title as description, created_at 
                FROM posts 
                ORDER BY created_at DESC 
                LIMIT 10
            ");
            $posts = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

            // 最近的用户注册
            $stmt = $db->query("
                SELECT 'user' as type, CONCAT('用户 ', username, ' 注册') as description, created_at 
                FROM users 
                ORDER BY created_at DESC 
                LIMIT 10
            ");
            $users = $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];

            // 合并并按时间排序
            $activities = array_merge($posts, $users);
            usort($activities, function ($a, $b) {
                return strtotime($b['created_at']) - strtotime($a['created_at']);
            });

            $activities = array_slice($activities, 0, 10);
        } catch (\Throwable $e) {
            error_log("Recent activity error: " . $e->getMessage());
        }

        return $activities;
    }
}
